package com.android.hedgehog.puzzles;

import java.util.Random;

public class SeesawBoard2 {
	public SeesawBlock2[] blocks;
	Random rand = new Random();
	int position, weight;
	int weightLimit; // 0-5: 1; 6-10: 2
	int totalBoardValue; // if < 0, then more weight on left
	int maximumBoardValue;
	int[] boardPositionCounter = new int[6];// counts # of blocks on pos
	boolean boardMaxHeightReached; // too much blocks on 1 position
	int maxHeightLimit = 5; // max # of blocks on any pos
	public int leftBoardTotalValue;
	public int rightBoardTotalValue;
	public String test;

	public SeesawBoard2(int difficulty) {
		setDifficulty(difficulty);
		setBlocks();
		setPosition();
		addTotal();
		test = "D: " + difficulty + "  total: " + totalBoardValue + " M:" + maximumBoardValue;

	}

	private void setDifficulty(int difficulty) {
		blocks = new SeesawBlock2[8 + difficulty];
		weightLimit = 1 + (9 * difficulty);
		maximumBoardValue = 6 - ((difficulty + 1) / 2);
	}

	/**
	 * doWhile loop runs until totalBoardValue is between -maximumBoardValue &
	 * +maximumBoardValue. And height of blocks does not go past five.
	 */
	private void setBlocks() {

		do {

			// reset
			totalBoardValue = 0;
			boardMaxHeightReached = false;
			for (int i = 0; i < boardPositionCounter.length; i++)
				boardPositionCounter[i] = 0;

			// set position & weight and get total board value
			for (int i = 0; i < blocks.length; i++) {
				position = rand.nextInt(6);
				weight = rand.nextInt(weightLimit);
				blocks[i] = new SeesawBlock2(position, weight);
				totalBoardValue += blocks[i].value;
			}

			// check to make sure height doesn't go past 5
			for (int i = 0; i < blocks.length; i++) {
				boardPositionCounter[blocks[i].boardXOrder]++;
				if (boardPositionCounter[blocks[i].boardXOrder] > maxHeightLimit)
					boardMaxHeightReached = true;
			}

		} while (totalBoardValue == 0 || Math.abs(totalBoardValue) > maximumBoardValue
				|| boardMaxHeightReached);

	}

	private void setPosition() {
		// reset
		for (int i = 0; i < boardPositionCounter.length; i++)
			boardPositionCounter[i] = 0;

		// set y coordinate
		for (int i = 0; i < blocks.length; i++) {
			blocks[i].setHeight(boardPositionCounter[blocks[i].boardXOrder] * -30);
			boardPositionCounter[blocks[i].boardXOrder]++;
		}

	}

	private void addTotal() {
		// counts total value on each side of board;
		for (int i = 0; i < blocks.length; i++) {
			if (blocks[i].boardXOrder < 3)
				leftBoardTotalValue += (blocks[i].value * -1);
			else
				rightBoardTotalValue += (blocks[i].value);
		}
	}

}
